Discordant Usage of Cast Operator and Check of Returned Value of qualificator method (DUCOCRV)

Description:

DUCOCRV detects incorrect type casts caused by incorrect usage of "type codes".

This error may occur when the type of an object in a hierarchy of classes is determined by examining the value returned by the qualificator method. A warning message is shown when the value returned by a qualificator method is compared with a constant that is returned by an implementation of the qualificator method in type A and then inside the same conditional branch the object is casted to type B that is not the same type as A and is not a base type of A.

Incorrect:

type

    Expression = class abstract

        public
         const UNARY: integer = 0;
         const BINARY: integer = 1;

        function getKind():integer;virtual;abstract;
    end;

    UnaryExpression = class(Expression)

        public
        function getKind():integer;override;
        function getOperand():Expression;
    end;

    BinaryExpression = class(Expression)

        public
        function getKind():integer;override;
        function getLeftOperand():Expression;
        function getRightOperand():Expression;
    end;

    Some = class

        public
        procedure eval(expr: Expression);
    end;


implementation

function UnaryExpression.getKind():integer;
begin
  result := UNARY;
end;

function BinaryExpression.getKind():integer;
begin
  result := BINARY;
end;

procedure Some.eval(expr: Expression);
begin
  if expr.getKind() = Expression.UNARY then
     eval((expr as BinaryExpression).getLeftOperand());
end;

Correct:

procedure Some.eval(expr: Expression);
begin
  if expr.getKind() = Expression.UNARY then
     eval((expr as UnaryExpression).getOperand());
end;